<template>
    <div style="height: calc(100vh - 118px);">
        <el-row :gutter="20">
            <el-col :span="24">
                <weather/>
            </el-col>
        </el-row>
        
        <el-card style="height: 220px;">
            <el-row style="height: 32px;">
                <el-col>
                    <el-col :span="12">
                        <span style="font-size: 20px;">今日计划： </span>
                    </el-col>
                    <el-col :span="12">
                        <div class="" style="float: right;">
                            <el-button type="success" size="small" plain class="btn" @click="addPlanForm()">新增计划</el-button>
                        </div>
                    </el-col>
                </el-col>
            </el-row>
            <div style="height: 135px;overflow: auto;"
                v-loading="loadingRask"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(255, 255, 255, 0.8)"
            >
                <div v-if="planList.length > 0">
                    <div v-for="(item, index) in planList" :key="index">
                        <div style="margin: 10px;position: relative; font-size: 16px;">
                            {{item.priority == 0 ? '' : '(优先级'+item.lvl+') | '}} 
                            <span>{{item.plan_desc}} | {{item.state}}</span>
                            <el-button type="primary" icon="el-icon-edit" circle size="mini" @click="editPlan(item)" style="position: absolute;right: 55px;"></el-button>
                            <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="delPlanForm(item)" style="position: absolute;right: 10px;"></el-button>
                        </div>
                    </div>
                </div>
                <div v-else style="text-align: center;line-height: 135px;height: 100%;">
                    暂无数据
                </div>
            </div>
        </el-card>

        <el-card style="overflow: auto;margin-top: 10px;height: calc(100vh - 558px);">
             <el-row style="height: 32px;">
                <el-col>
                    <el-col :span="12">
                        <span style="font-size: 20px;">今日复盘： </span>
                    </el-col>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6"  class="ttest">
                    <div class="" style="font-size: 18px;margin-bottom: 5px;">进行中计划 {{this.replay.start}} / {{this.replay.allPlans}}</div>
                    <div class="" style="font-size: 18px;margin-bottom: 5px;">已完成计划 {{this.replay.finist}} / {{this.replay.allPlans}}</div>
                    <div class="" style="font-size: 18px;margin-bottom: 5px;">未开始计划 {{this.replay.unstart}} / {{this.replay.allPlans}}</div>
                </el-col>
                <el-col :span="6">
                    <div style="padding-left: 20px;">优先级/计划名称</div>
                    <div id="pieEchart" ref="pieEchart" style="height: 114px;width: 470px;border: 0px solid;top: 0px;"></div>
                    <div  v-if="planList.length == 0" class="noEchartData">暂无数据</div>
                </el-col>
                <el-col :span="6">
                    <div style="position: relative;">
                        <bindundun style="position: absolute;right: 0px;top: -38px;"/>
                    </div>
                </el-col>
            </el-row>
        </el-card>

        <el-dialog :title="curFormDialog" :visible.sync="dialogFormVisible" custom-class="planForm">
            <el-form ref="planForm" :model="planForm" label-width="80px">
                <el-form-item label="计划名称" style="width: 500px;">
                    <el-input v-model="planForm.planName"></el-input>
                </el-form-item>
                <el-form-item label="起止时间" style="width: 500px;">
                    <el-date-picker
                        v-model="planForm.date"
                        value-format="yyyy-MM-dd HH:mm:00"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="优先级" style="width: 400px;">
                    <el-select v-model="planForm.lvl" placeholder="请选择">
                    <el-option label="I" value="1"></el-option>
                    <el-option label="II" value="2"></el-option>
                    <el-option label="III" value="3"></el-option>
                    <el-option label="IV" value="4"></el-option>
                    <el-option label="V" value="5"></el-option>
                    </el-select>
                </el-form-item>
            
                <el-form-item label="状态">
                    <el-radio-group v-model="planForm.state">
                        <el-radio label="未开始" ></el-radio>
                        <el-radio label="进行中" ></el-radio>
                        <el-radio label="已完成" ></el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closePlanForm()">取 消</el-button>
                <el-button type="primary" @click="surePlanForm()">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>


<script>
import bindundun from '@/components/bindundun';

import weather from "@/components/weather";
import echart from "vue-echarts";
import { addtoDayPlan, selecttoDayPlanByUserId, updatetoDayPlanbyId, deletetoDayPlan} from "@/api";

export default {
    components:{
        weather,
        bindundun
    },
    name: "index",
    data() {
        return {
            loadingRask: false,
            noDataEcharts: false,
            planList: [
                // {
                //     _id: undefined,
                //     user_id: undefined,
                //     plan_desc: '健身一个小时1',
                //     priority: 1, // 优先级
                //     lvl: 'I',
                //     begin_time: '',
                //     end_time: '',
                //     state: '未开始', // 未开始 | 进行中 | 已完成
                // },
                // {
                //     _id: undefined,
                //     user_id: undefined,
                //     plan_desc: '健身一个小时2',
                //     priority: 1,
                //     lvl: 'I',
                //     begin_time: '',
                //     end_time: '',
                //     state: '未开始',
                // },
                // {
                //     _id: undefined,
                //     user_id: undefined,
                //     plan_desc: '健身一个小时3',
                //     priority: 1,
                //     lvl: 'I',
                //     begin_time: '',
                //     end_time: '',
                //     state: '未开始',
                // },
            ],
            curFormDialog: '新建计划',
            planForm: { // 计划form
                planName: '',
                date: [],
                lvl: '',
                state: '未开始', // 默认
            },
            dialogFormVisible: false,
            replay: {
                allPlans: 0, // 所有计划
                start: 0, // 进行中
                finist: 0, // 已完成
                unstart: 0, // 未开始
            }
        }
    },
    methods:{
        // 复盘
        dealReplay(planList) {
            //console.log('planList', planList);
            this.replay.allPlans = planList.length;
            this.replay.start = 0;
            this.replay.finist = 0;
            this.replay.unstart = 0;

            planList.forEach((ele) => {
                if(ele.state == '未开始') {
                    this.replay.unstart += 1;
                } else if (ele.state == '已完成') {
                    this.replay.finist += 1;
                } else if(ele.state == '进行中') {
                    this.replay.start += 1;
                }
            });
        },
        // 【接口调用 查询计划】加载计划
        loadPlanList() {
            this.loadingRask = true;
            this.noDataEcharts = true;
            this.planList = [];
            let user = window.sessionStorage.getItem('user');
            let dealUser = JSON.parse(user);

            let param = {
                page: 1,
                limit: 10000,
                user_id: dealUser._id,
                state: '',
            };
            // 查询指定用户的今日计划(含复盘）（分页）
            selecttoDayPlanByUserId(param).then((res) => {
                this.loadingRask = false;
                if(res.data.code ===200){
                    this.$message.success("加载成功！")
                    if (res.data.data.length > 0) {
                        this.noDataEcharts = false; // 暂无图表数据
                        res.data.data.forEach((ele) => {
                            // debugger;
                            let obj = {
                                plan_desc: ele.plan_desc,
                                priority: ele.priority,
                                begin_time: ele.begin_time,
                                end_time: ele.end_time,
                                state: ele.state,
                                _id: ele._id,
                                user_id: ele.user_id,
                                lvl: 'I',
                            }
                            // debugger;
                            switch(ele.priority) {
                                case '1': obj.lvl = 'I'; break;
                                case '2': obj.lvl = 'II'; break;
                                case '3': obj.lvl = 'III'; break;
                                case '4': obj.lvl = 'IV'; break;
                                case '5': obj.lvl = 'V'; break;
                                default: obj.lvl = 'I';
                            }
                            this.planList.push(obj)
                        });
                        // console.log(this.planList);
                        // 复盘
                        // debugger;
                        this.dealReplay(res.data.data);
                        this.drawPie(res.data.data);
                    }
                    // console.log(res.data.data);
                }
            });
        },
        // 重置计划弹框
        resetPlanForm() {
            this.planForm._id = undefined;
            this.planForm.user_id = undefined;
            this.planForm.planName = '',
            this.planForm.lvl = '';
            this.planForm.date = '';
            this.planForm.state = '未开始'; // 默认
        },
        // 新建计划弹框
        addPlanForm() {
            this.resetPlanForm();
            this.curFormDialog = '新建计划';
            this.dialogFormVisible = true;
        },
        // 关闭计划弹框
        closePlanForm() {
            this.dialogFormVisible = false;
        },
        // 【接口调用 录入计划 / 编辑计划】保存 计划弹框
        surePlanForm() {
            if (this.planForm.planName == '') {
                this.$message({
                    showClose: true,
                    message: '计划名称不能为空',
                    type: 'warning'
                });
                return;
            }
            if (this.planForm.lvl == '') {
                this.$message({
                    showClose: true,
                    message: '请设置任务优先级',
                    type: 'warning'
                });
                return;
            }
            if (this.planForm.date.length == 0) {
                this.$message({
                    showClose: true,
                    message: '请设置任务时间',
                    type: 'warning'
                });
                return;
            }

            // 添加计划
            if (!this.planForm.user_id) {
                // 获取用户信息
                let user = window.sessionStorage.getItem('user');
                let dealUser = JSON.parse(user);
                let params = {
                    user_id: dealUser._id,
                    plan_desc: this.planForm.planName,
                    priority: this.planForm.lvl,
                    begin_time: this.planForm.date[0],
                    end_time: this.planForm.date[1],
                    state: '未开始', // 默认
                    is_delete: false,
                }
                // console.log(params);
                addtoDayPlan(params).then((res) => {
                    //console.log(res);
                    if(res.data.code ===200){
                        this.$message.success("新增成功！")
                        this.dialogFormVisible = false;
                        // 刷新计划
                        this.loadPlanList();
                    }
                }).catch((msg) => {
                    // 添加计划失败的回调
                    this.$message({
                        showClose: true,
                        message: msg,
                        type: 'error'
                    });
                    setTimeout(() => {
                        this.dialogFormVisible = false;
                    }, 5000);
                });
            } else {
                // 编辑计划
                let params = {
                    _id: this.planForm._id,
                    user_id: this.planForm.user_id,
                    plan_desc: this.planForm.planName,
                    priority: this.planForm.lvl,
                    begin_time: this.planForm.date[0],
                    end_time: this.planForm.date[1],
                    state: this.planForm.state,
                    is_delete: false,
                }
                updatetoDayPlanbyId(params).then((res) => {
                    //console.log(res);
                    if(res.data.code ===200){
                        this.$message.success("更新成功！")
                        this.dialogFormVisible = false;
                        // 刷新计划
                        this.loadPlanList();
                    }
                })
            }  
        },
        // 编辑 计划弹框
        editPlan(item) {
            //console.log('单个', item);
            this.curFormDialog = '编辑计划';
            this.dialogFormVisible = true;
            //console.log(item);
            this.planForm.planName = item.plan_desc,
            this.planForm.lvl = item.lvl;
            this.planForm.date = [item.begin_time, item.end_time];
            this.planForm.state = item.state; // 默认
            this.planForm._id = item._id;
            this.planForm.user_id= item.user_id;
        },
        // 删除计划弹框
        delPlanForm(item) {
            this.$confirm('即将删除计划, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deletetoDayPlan(item._id).then((res) => {
                    if (res.data.code===200){
                        this.$message.success("删除成功");
                        this.loadPlanList();
                    }
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        // 加载图表
        drawPie(data) {
            let XData = [];
            let YData = [];
            if (data.length <= 0) {
                return;
            }
            data.forEach((ele) => {
                XData.push(ele.plan_desc);
                YData.push(ele.priority);
            });
            //console.log('书记', data);
            let bingtu_dv = this.$refs.pieEchart;
            if (bingtu_dv) {
                let bingtu = this.$echarts.init(bingtu_dv);
                // 绘制图表
                bingtu.setOption({
                    tooltip: {
                        trigger: "axis",
                        axisPointer: {
                            type: "cross",
                            label: {
                            backgroundColor: "#6a7985",
                            },
                        },
                        formatter: function(params) {
                            // console.log(params);
                            let tip = params[0].value;
                            let retTxt = '';
                            switch(tip) {
                                case '1': retTxt = 'I'; break;
                                case '2': retTxt = 'II'; break;
                                case '3': retTxt = 'III'; break;
                                case '4': retTxt = 'IV'; break;
                                case '5': retTxt = 'V'; break;
                                default: retTxt = 'I';
                            }
                            return '优先级（' + retTxt + '）';
                        }
                    },
                    grid: {
                    top: "6%",
                    left: "6%",
                    right: "6%",
                    bottom: "3%",
                    containLabel: true,
                    },
                    xAxis: {
                    type: "category",
                    data: XData,
                    axisLabel: {
                        // 坐标轴刻度标签的相关设置。
                        formatter(params) {
                        let newParamsName = ""; // 最终拼接成的字符串
                        const paramsNameNumber = params.length; // 实际标签的个数
                        const provideNumber = 10; // 每行能显示的字的个数
                        const rowNumber = Math.ceil(paramsNameNumber / provideNumber); // 换行的话，需要显示几行，向上取整
                        /**
                         * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
                         */
                        // 条件等同于rowNumber>1
                        if (paramsNameNumber > provideNumber) {
                            /** 循环每一行,p表示行 */
                            // eslint-disable-next-line no-plusplus
                            for (let p = 0; p < rowNumber; p++) {
                            let tempStr = ""; // 表示每一次截取的字符串
                            const start = p * provideNumber; // 开始截取的位置
                            const end = start + provideNumber; // 结束截取的位置
                            // 此处特殊处理最后一行的索引值
                            if (p === rowNumber - 1) {
                                // 最后一次不换行
                                tempStr = params.substring(start, paramsNameNumber);
                            } else {
                                // 每一次拼接字符串并换行
                                tempStr = `${params.substring(start, end)}\n`;
                            }
                            newParamsName += tempStr; // 最终拼成的字符串
                            }
                        } else {
                            // 将旧标签的值赋给新标签
                            newParamsName = params;
                        }
                        // 将最终的字符串返回
                        return newParamsName;
                        },
                    },
                    },
                    yAxis: {
                    type: "value",
                    },
                    series: [
                    {
                        data: YData,
                        type: "line",
                        smooth: true, // true: 折线变成曲线
                        itemStyle: { normal: { color: "#47a6ff" } },
                        areaStyle: {
                        normal: {
                            color: new echart.graphic.LinearGradient(0, 0, 0, 1, [
                            // 这里用到了echart
                            {
                                offset: 0,
                                color: "#47a6ff",
                            },
                            {
                                offset: 1,
                                color: "#fff",
                            },
                            ]),
                        },
                        },
                    },
                    ],
                });
            }
        },
    },
    mounted() {
        this.loadPlanList();
    }
}
</script>

<style scoped lang="scss">
.btn{
    text-align: center;
}

.el-input__inner{
    width: 420px;
}
::v-deep .el-select .el-input{
    width: 420px;
}
.echarts{
    width: 500px;
    height: 500px;

}

.ttest {
    position: relative;
    &::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        border: 2px solid #c2e7b0;
        animation: clippath 3s infinite linear;
    }
}

@keyframes clippath {
    0%,
    100% {
        clip-path: inset(0 0 95% 0);
    }
    25% {
        clip-path: inset(0 95% 0 0);
    }
    50% {
        clip-path: inset(95% 0 0 0);
    }
    75% {
        clip-path: inset(0 0 0 95%);
    }
}

.noEchartData {
    text-align: center;
    height: 114px;
    line-height: 114px;
    position: absolute;
    top: 0px;
    left: 50%;
}
</style>